package cn.tedu.boot52.controller;

import cn.tedu.boot52.entity.User;
import cn.tedu.boot52.entity.Weibo;
import cn.tedu.boot52.mapper.WeiboMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/send")
    public int send(Weibo weibo, MultipartFile picFile, HttpSession session) throws IOException {
        //取出当前登入的用户对象
        User user = (User) session.getAttribute("user");
        if (user == null) {//代表未登入
            return 2;
        }
        //得到原始文件名
        String fileName = picFile.getOriginalFilename();
        //得到后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名
        fileName = UUID.randomUUID() + suffix;
        //文件夹路径
        String dirPath = "E:/upload/";
        File dirFile = new File(dirPath);
        //判断如果文件夹不存在在创建
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //得到图片的完整路径
        String filePath = dirPath + fileName;
        //保存文件  异常抛出
        picFile.transferTo(new File(filePath));
        //给weibo对象添加各种值
        weibo.setAuthor(user.getNick());//作者昵称
        weibo.setUserId(user.getId());//作者id
        weibo.setCreated(new Date());//设置发布时间,new Date()得到当前的日期对象
        weibo.setUrl("/" + fileName);//保存图片名
        //把微博对象的数据保存到weibo表中
        mapper.insert(weibo);
        return 1;//代表发布成功
    }
    @RequestMapping("/select")
    public List<Weibo> select(){
        return mapper.select();
    }
    @RequestMapping("/selectById")
    public Weibo selectById(int id){
        return mapper.selectById(id);
    }

}